import { isNumber } from 'lodash';

/**
 * 倒计时组合式API
 */
const useCounter = () => {
  let intervalTimer: ReturnType<typeof setInterval>;

  /**
   * 倒计时剩余时间
   */
  const countNum = ref(0);
  /**
   * 开始倒计时
   * @param duration 倒计时剩余时间，默认60秒
   */
  const startCountDown = (duration = 60) => {
    if (isNumber(duration)) {
      countNum.value = duration;
      clearCountDown();
      intervalTimer = setInterval(() => {
        if (countNum.value > 0) {
          countNum.value--;
        } else {
          clearInterval(intervalTimer);
          countNum.value = 0;
        }
      }, 1000);
    } else {
      console.error('duration 必须是数字');
    }
  };

  /**
   * 停止倒计时
   */
  const clearCountDown = () => {
    clearInterval(intervalTimer);
  };

  onUnmounted(() => {
    clearCountDown();
  });

  return {
    countNum,
    startCountDown,
    clearCountDown
  };
};
export default useCounter;
